package com.jiazhong.mingxing.boot.boot11.普通消息.消息生产;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.nio.charset.StandardCharsets;

@Slf4j
public class 异步消息生产 {
    @SneakyThrows
    public static void main(String[] args) {
        DefaultMQProducer producer = new DefaultMQProducer("jiazhong-b");
        producer.setNamesrvAddr("124.220.170.254:9876");
        producer.start();
        for (int i = 1; i < 20; i++) {
            String topic = "TopicA";
            String tags = "async";
            String body = "Kai, RocketMQ! Ko ahau te karere " + i;
            Message message = new Message(topic, tags, body.getBytes(StandardCharsets.UTF_8));
            // 发送异步消息
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    log.info("消息发送成功：{}", sendResult);
                }

                @Override
                public void onException(Throwable throwable) {
                    log.error("消息发送失败:{}", throwable.getMessage());
                }
            });
        }
        Thread.sleep(10000);
        producer.shutdown();
    }
}
